<template>
    <el-dialog v-model="props.modelValue" style="margin-top:70px;" @close="hideModal" append-to-body>
        <template #header>
            <div class="text-center font-bold text-[18px]">
                {{ '商品图片' }}
            </div>
        </template>
        <multiple-upload ref="multipleUploadRef" v-model="state.images" />
        <div v-if="state.savedImage.length">
            <p class="font-bold text-[18px] my-[20px]">已上传图片</p>
            <ul class="flex flex-1 flex-wrap justify-start">
                <li class="m-2 relative" v-for="(item, index) in state.savedImage" :key="item.url">
                    <el-image fit="cover" class="w-[150px] h-[150px]" :src="item.url" @click="viewImage(item)" />
                    <span class="absolute right-0 top-1 w-[25px] h-[25px]" @click="handleRemove(item)">
                        <el-icon :size="20" color="red"><i-ep-Delete /></el-icon>
                    </span>
                </li>
            </ul>
        </div>
        <el-dialog v-model="state.dialogVisible">
            <div class="flex justify-center">
                <img w-full :src="state.dialogImageUrl" alt="Preview Image" />
            </div>
        </el-dialog>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" type="success" @click="addProductImage">提交</el-button>
                <el-button size="large" type="primary" @click="hideModal">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup>
import { Product, ProductImage } from './type';

type Props = {
    modelValue: boolean,
    data: Product,
    closeFun?: Function,
}

type State = {
    showImage: boolean;
    currentProduct: Product;
    images: ProductImage[];
    savedImage: ProductImage[];
    dialogVisible: boolean;
    dialogImageUrl: string;
}

const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits([
    "update:modelValue",
    "update:currentProduct",
]);
const state = reactive<State>({
    showImage: false,
    currentProduct: {} as Product,
    images: [],
    savedImage: [],
    dialogVisible: false,
    dialogImageUrl: '',
})
const multipleUploadRef = ref(null)

watch(() => props.data,
    (newV, oldV) => {
        state.currentProduct = newV
        loadImages()
    })

const hideModal = () => {
    emit("update:modelValue", false)
    const { currentProduct } = state
    const _ = multipleUploadRef.value as any
    _?.resetImage?.()
    state.images = []
    props?.closeFun?.(currentProduct)
}

const singleSubmit = async (refGuid: string, name: string, url: string, hash: string) => {
    const params = {
        type: 1, // 商品
        refGuid,
        name,
        url,
        hash,
    }
    return await CommonService.uploadImageList(params)
}

const addProductImage = async () => {
    emit("update:modelValue", false)
    const { currentProduct, images } = state
    const temp = [...images], errList = []

    Utils.Modal().loading('请求中~')
    while (temp.length) {
        const current = temp.shift() as { name: string, url: string, hash: string }
        const { name, url, hash } = current
        const [err, res] = await singleSubmit(currentProduct.pId, name, url, hash)
        if (err) errList.push(current)
    }

    Utils.Modal().closeLoading()
    hideModal()

    if (errList.length) {
        Utils.Modal().alert(`存在${errList.length}张保存失败,请检查后重试~`)
    } else {
        Utils.Modal().msgSuccess('提交成功~')
    }
}

const loadImages = async () => {
    const { currentProduct } = state
    const [err, res] = await CommonService.loadImageByRefGuid({ refGuid: currentProduct.pId, type: 1 })
    if (err) return Utils.Modal().msgError(err)
    state.savedImage = res.data
}

const viewImage = (item: ProductImage) => {
    state.dialogVisible = true
    state.dialogImageUrl = item.url
}

const handleRemove = async (item: ProductImage) => {
    Utils.Modal().loading('上传中~')
    const { savedImage } = state
    const [err, res] = await CommonService.deleteImageByGuid({ hash: item.hash })
    Utils.Modal().closeLoading()
    // if (err) return Utils.Modal().msgError(err)
    if (err) console.log('CommonService.deleteImageByGuid :>> ', err)
    state.savedImage = savedImage.filter(_ => _.guid != item.guid)
}
</script>

<style lang='scss' scoped></style>